using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;using THSERP.BusinessEntities;using THSERP.BaseProvider;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraTreeList.Nodes;
using THSLib;using THSERP.BaseProvider;
using System.Security.Cryptography;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraTreeList;
using DevExpress.XtraTreeList.Nodes;

namespace THSERP.Modules.UserManagement
{
    public partial class guiUserManagement : THSERPScreen
    {
        THSList<STModulesInfo> lstModule = new THSList<STModulesInfo>(); 

        public guiUserManagement()
        {
            InitializeComponent();

            lstModule = new THSList<STModulesInfo>();
            InitializePrivilegeGridView();
            ShowAllModule();
        }

        private void fld_trlstUserGroup_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                TreeListNode node = fld_trlstUserGroup.FocusedNode;
                if (node != null)
                {
                    String strNodeValue =Convert.ToString(node.GetValue(fld_tlcUserGroupName));
                    if (strNodeValue == "User Group")
                    {
                        ContextMenu popupMenu = new ContextMenu();
                        popupMenu.MenuItems.Add("Add User Group", new EventHandler(AddUserGroup_Clicked));
                        popupMenu.Show(fld_trlstUserGroup, new Point(e.X, e.Y));
                       
                    }
                    else if (node.Level == 1)
                    {
                        ContextMenu popupMenu = new ContextMenu();
                        popupMenu.MenuItems.Add("Add Section", new EventHandler(AddSection_Clicked));
                        popupMenu.MenuItems.Add("Edit User Group", new EventHandler(EditUserGroup_Clicked));
                        popupMenu.MenuItems.Add("Delete User Group", new EventHandler(DeleteUserGroup_Clicked));
                        popupMenu.Show(fld_trlstUserGroup, new Point(e.X, e.Y));
                    }
                    else if(node.Level == 2)
                    {
                        ContextMenu popupMenu = new ContextMenu();
                        popupMenu.MenuItems.Add("Add/Remove Modules", new EventHandler(AddModule_Clicked));
                        popupMenu.MenuItems.Add("Edit Section", new EventHandler(EditSection_Clicked));
                        popupMenu.MenuItems.Add("Delete Section", new EventHandler(DeleteSection_Clicked));
                        popupMenu.Show(fld_trlstUserGroup, new Point(e.X, e.Y));
                    }
                }
            }
        }

        public void AddUserGroup_Clicked(object sender, EventArgs e)
        {
            guiAddUserGroups _guiAddUserGroups = new guiAddUserGroups(fld_trlstUserGroup);
            _guiAddUserGroups.Module = this.Module;
            _guiAddUserGroups.ShowDialog();
        }

        public void EditUserGroup_Clicked(object sender, EventArgs e)
        {
            guiAddUserGroups guiAddUserGroups = new guiAddUserGroups(fld_trlstUserGroup);
            guiAddUserGroups.Module = this.Module;
            guiAddUserGroups.fld_txtUserGroup.Text = fld_trlstUserGroup.FocusedNode.GetDisplayText(fld_trlstUserGroup.Columns[0]);
            guiAddUserGroups.ShowDialog();
        }

        public void AddSection_Clicked(object sender, EventArgs e)
        {
            guiAddSections _guiAddSections = new guiAddSections(fld_trlstUserGroup);
            _guiAddSections.Module = this.Module;
            _guiAddSections.ShowDialog();
        }

        public void EditSection_Clicked(object sender, EventArgs e)
        {
            guiAddSections guiAddSections = new guiAddSections(fld_trlstUserGroup);
            guiAddSections.Module = this.Module;
            guiAddSections.fld_txtSection.Text = fld_trlstUserGroup.FocusedNode.GetDisplayText(fld_trlstUserGroup.Columns[0]);
            guiAddSections.ShowDialog();
        }

        public void DeleteSection_Clicked(object sender, EventArgs e)
        {
            if (MessageBox.Show("Do you want to delete this section?", "#Message#", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                TreeListNode node = fld_trlstUserGroup.FocusedNode;
                ADUserGroupSectionsController objUserGroupSectionsController = new ADUserGroupSectionsController();
                STModuleToUserGroupSectionsController objModuleToUserGroupSectionsController = new STModuleToUserGroupSectionsController();

                DataSet ds = objModuleToUserGroupSectionsController.GetAllModuleToUserGroupSectionByUserGroupSectionID((int)node.Tag);
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    STModuleToUserGroupSectionsInfo objModuleToUserGroupSectionsInfo = (STModuleToUserGroupSectionsInfo)objModuleToUserGroupSectionsController.GetObjectFromDataRow(row);
                    objModuleToUserGroupSectionsController.DeleteObject(objModuleToUserGroupSectionsInfo.STModuleToUserGroupSectionID);
                }

                objUserGroupSectionsController.DeleteObject((int)node.Tag);
                ((UserManagementModule)Module).InitializeTreeList(fld_trlstUserGroup);
            }
        }

        public void DeleteUserGroup_Clicked(object sender, EventArgs e)
        {
            if (MessageBox.Show("Do you want to delete this user group?", "#Message#", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                TreeListNode node = fld_trlstUserGroup.FocusedNode;
                ADUserGroupsController objUserGroupsController = new ADUserGroupsController();
                ADUserGroupsInfo objUserGroupsInfo = (ADUserGroupsInfo)objUserGroupsController.GetObjectByID((int)node.Tag);
                objUserGroupsController.DeleteObject(objUserGroupsInfo.ADUserGroupID);
                ((UserManagementModule)Module).InitializeTreeList(fld_trlstUserGroup);
            }
        }

        public void AddModule_Clicked(object sender, EventArgs e)
        {
            guiAddModules _guiAddModules = new guiAddModules(fld_trlstUserGroup);
            _guiAddModules.Module = this.Module;
            _guiAddModules.ShowDialog();
        }

        public void ShowAllModule()
        {
            STModulesController objModulesController = new STModulesController();
            DataSet ds = objModulesController.GetAllObjects();
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                STModulesInfo objModulesInfo = (STModulesInfo)objModulesController.GetObjectFromDataRow(row);
                STModuleDescriptionsController objModuleDescriptionsController = new STModuleDescriptionsController();
                fld_lstPermission.Items.Add(((STModuleDescriptionsInfo)objModuleDescriptionsController.GetObjectByModuleID(objModulesInfo.STModuleID)).STModuleDescriptionDescription);
            }
        }

        /// <summary>
        /// Show privilege list to modify
        /// </summary>
        /// <remarks>Hieu.nguyen_26/04/2010</remarks>

        public void InitializePrivilegeGridView()
        {
            GridView gridView = fld_dgvPrivilege;
            gridView.OptionsSelection.EnableAppearanceFocusedCell = false;
            gridView.OptionsSelection.EnableAppearanceFocusedRow = false;

            gridView.Columns.AddVisible("ADPrivilegeCaption");
            gridView.Columns["ADPrivilegeCaption"].OptionsColumn.AllowEdit = false;
            gridView.Columns["ADPrivilegeCaption"].AppearanceCell.BackColor = Color.WhiteSmoke;
            gridView.Columns["ADPrivilegeCaption"].Caption = "Privileges";

            ADUserGroupsController objUserGroupsController = new ADUserGroupsController();
            THSList<ADUserGroupsInfo> lstUserGroups = new THSList<ADUserGroupsInfo>();
            lstUserGroups.InitTHSList(null, String.Empty, THSUtil.GetTableNameFromBusinessObjectType(typeof(ADUserGroupsInfo)));
            DataSet ds1 = objUserGroupsController.GetAllObjects();
            lstUserGroups.Invalidate(ds1);
            foreach (ADUserGroupsInfo objUserGroupsInfo in lstUserGroups)
            {
                gridView.Columns.AddVisible(objUserGroupsInfo.ADUserGroupName);
            }
            
        }

        public void ShowPrivileges()
        {
            STModuleDescriptionsController objModuleDescriptionsController = new STModuleDescriptionsController();
            int moduleID = ((STModuleDescriptionsInfo)objModuleDescriptionsController.GetObjectByDescription((String)fld_lstPermission.SelectedItem)).STModuleID;

            STModulesController objModulesController = new STModulesController();
            //STModulesInfo objSTModulesInfo = (STModulesInfo)objModulesController.GetObjectByName((String)fld_lstPermission.SelectedItem);
            STModulesInfo objSTModulesInfo = (STModulesInfo)objModulesController.GetObjectByID(moduleID);
            ADPrivilegesController objPrivilegesController = new ADPrivilegesController();
            DataSet ds = objPrivilegesController.GetAllDataByForeignColumn("FK_STModuleID", (int)objSTModulesInfo.STModuleID);
            if (ds.Tables[0] != null)
            {
                ADUserGroupsController objUserGroupsController = new ADUserGroupsController();
                THSList<ADUserGroupsInfo> lstUserGroups = new THSList<ADUserGroupsInfo>();
                lstUserGroups.InitTHSList(null, String.Empty, THSUtil.GetTableNameFromBusinessObjectType(typeof(ADUserGroupsInfo)));
                DataSet ds1 = objUserGroupsController.GetAllObjects();
                lstUserGroups.Invalidate(ds1);

                foreach (ADUserGroupsInfo objUserGroupsInfo in lstUserGroups)
                {
                    DataColumn column = new DataColumn(objUserGroupsInfo.ADUserGroupName, typeof(bool));
                    ds.Tables[0].Columns.Add(column);
                    foreach (DataRow row in ds.Tables[0].Rows)
                    {
                        ADPrivilegesInfo objPrivilegesInfo = (ADPrivilegesInfo)objPrivilegesController.GetObjectFromDataRow(row);
                        ADPrivilegeUserGroupsController objPrivilegeUserGroupsController = new ADPrivilegeUserGroupsController();
                        ADPrivilegeUserGroupsInfo objPrivilegeUserGroupsInfo = (ADPrivilegeUserGroupsInfo)objPrivilegeUserGroupsController.GetObjectByPrivilegeIDAndUserGroupID(objPrivilegesInfo.ADPrivilegeID, objUserGroupsInfo.ADUserGroupID);

                        if (objPrivilegeUserGroupsInfo == null || objPrivilegeUserGroupsInfo.ADPrivilegeUserGroupCheck == false)
                        {
                            row[objUserGroupsInfo.ADUserGroupName] = false;
                        }
                        else
                            row[objUserGroupsInfo.ADUserGroupName] = true;
                    }
                }
                fld_dgcPrivilege.DataSource = ds.Tables[0];
                fld_dgvPrivilege.RefreshData();
            }
        }

        private void fld_lstPermission_SelectedIndexChanged(object sender, EventArgs e)
        {
            ShowPrivileges();
        }

        private void fld_dgvPrivilege_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            DataRow row = fld_dgvPrivilege.GetDataRow(e.RowHandle);
            ADPrivilegesController objPrivilegesController = new ADPrivilegesController();
            ADPrivilegesInfo objPrivilegesInfo = (ADPrivilegesInfo)objPrivilegesController.GetObjectFromDataRow(row);
            ADPrivilegeUserGroupsController objPrivilegeUserGroupsController = new ADPrivilegeUserGroupsController();
            ADUserGroupsController objUserGroupsController = new ADUserGroupsController();
            int userGroupID = objUserGroupsController.GetObjectIDByName(e.Column.FieldName);
            ADPrivilegeUserGroupsInfo objPrivilegeUserGroupsInfo = objPrivilegeUserGroupsController.GetObjectByPrivilegeIDAndUserGroupID(objPrivilegesInfo.ADPrivilegeID, userGroupID);
            if (objPrivilegeUserGroupsInfo == null)
            {
                //Create new
                ADPrivilegeUserGroupsInfo objADPrivilegeUserGroupsInfo = new ADPrivilegeUserGroupsInfo();
                objADPrivilegeUserGroupsInfo.FK_ADPrivilegeID = objPrivilegesInfo.ADPrivilegeID;
                objADPrivilegeUserGroupsInfo.FK_ADUserGroupID = userGroupID;
                objADPrivilegeUserGroupsInfo.ADPrivilegeUserGroupCheck = (bool)e.Value;
                objPrivilegeUserGroupsController.CreateObject(objADPrivilegeUserGroupsInfo);
            }
            else
            {
                //Update
                objPrivilegeUserGroupsInfo.ADPrivilegeUserGroupCheck = (bool)e.Value;
                objPrivilegeUserGroupsController.UpdateObject(objPrivilegeUserGroupsInfo);
            }
        }

        #region Do drag/drop
        /// <summary>
        /// Do drag/drop tree list
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <remarks>Hieu.nguyen_04/05/2010</remarks>
        
        private TreeListHitInfo downHitInfo;

        private void fld_trlstUserGroup_DragDrop(object sender, DragEventArgs e)
        {
            TreeListHitInfo hitInfo = fld_trlstUserGroup.CalcHitInfo(fld_trlstUserGroup.PointToClient(new Point(e.X, e.Y)));
            TreeListNode targetNode = hitInfo.Node;
            TreeListNode sourceNode = downHitInfo.Node;
            if (targetNode != null)
            {
                if (targetNode.Level == 3 && sourceNode.Level == 3 && targetNode.ParentNode == sourceNode.ParentNode)
                {
                    STModuleToUserGroupSectionsController objSTModuleToUserGroupSectionController = new STModuleToUserGroupSectionsController();
                    STModuleToUserGroupSectionsInfo objModuleToUserGroupSectionsInfoSource = (STModuleToUserGroupSectionsInfo)objSTModuleToUserGroupSectionController.GetModuleToUserGroupSectionByUserGroupSectionIDAndModuleID((int)sourceNode.ParentNode.Tag, (int)sourceNode.Tag);
                    STModuleToUserGroupSectionsInfo objModuleToUserGroupSectionsInfoTarget = (STModuleToUserGroupSectionsInfo)objSTModuleToUserGroupSectionController.GetModuleToUserGroupSectionByUserGroupSectionIDAndModuleID((int)targetNode.ParentNode.Tag, (int)targetNode.Tag);

                    int sortOrderSrc = objModuleToUserGroupSectionsInfoSource.STModuleToUserGroupSectionSortOrder;
                    objModuleToUserGroupSectionsInfoSource.STModuleToUserGroupSectionSortOrder = objModuleToUserGroupSectionsInfoTarget.STModuleToUserGroupSectionSortOrder;
                    objModuleToUserGroupSectionsInfoTarget.STModuleToUserGroupSectionSortOrder = sortOrderSrc;

                    //Update
                    objSTModuleToUserGroupSectionController.UpdateObject(objModuleToUserGroupSectionsInfoSource);
                    objSTModuleToUserGroupSectionController.UpdateObject(objModuleToUserGroupSectionsInfoTarget);
                    //((UserManagementModule)Module).InitializeTreeList(fld_trlstUserGroup);
                    ((UserManagementModule)Module).RefreshTreeList(fld_trlstUserGroup, targetNode);

                }
                else if (targetNode.Level == 2 && sourceNode.Level == 2 && targetNode.ParentNode == sourceNode.ParentNode)
                {
                    ADUserGroupSectionsController objUserGroupSectionsController = new ADUserGroupSectionsController();
                    ADUserGroupSectionsInfo objUserGroupSectionsInfoSource = (ADUserGroupSectionsInfo)objUserGroupSectionsController.GetObjectByID((int)sourceNode.Tag);
                    ADUserGroupSectionsInfo objUserGroupSectionsInfoTarget = (ADUserGroupSectionsInfo)objUserGroupSectionsController.GetObjectByID((int)targetNode.Tag);

                    int sortOrderSrc = objUserGroupSectionsInfoSource.ADUserGroupSectionSortOrder;
                    objUserGroupSectionsInfoSource.ADUserGroupSectionSortOrder = objUserGroupSectionsInfoTarget.ADUserGroupSectionSortOrder;
                    objUserGroupSectionsInfoTarget.ADUserGroupSectionSortOrder = sortOrderSrc;

                    //Update
                    objUserGroupSectionsController.UpdateObject(objUserGroupSectionsInfoSource);
                    objUserGroupSectionsController.UpdateObject(objUserGroupSectionsInfoTarget);
                    //((UserManagementModule)Module).InitializeTreeList(fld_trlstUserGroup);
                    ((UserManagementModule)Module).RefreshTreeList(fld_trlstUserGroup, targetNode);
                }
               else if(targetNode.Level == 2 && sourceNode.Level == 3 && targetNode.ParentNode != sourceNode.ParentNode)
                {
                    ADUserGroupSectionsController objUserGroupSectionsController = new ADUserGroupSectionsController();
                    STModuleToUserGroupSectionsController objSTModuleToUserGroupSectionController = new STModuleToUserGroupSectionsController();
                    STModuleToUserGroupSectionsInfo objModuleToUserGroupSectionsInfoSource = (STModuleToUserGroupSectionsInfo)objSTModuleToUserGroupSectionController.GetModuleToUserGroupSectionByUserGroupSectionIDAndModuleID((int)sourceNode.ParentNode.Tag, (int)sourceNode.Tag);
                    ADUserGroupSectionsInfo objUserGroupSectionsInfoTarget = (ADUserGroupSectionsInfo)objUserGroupSectionsController.GetObjectByID((int)targetNode.Tag);
                    int iOrderIndex = targetNode.Nodes.Count;
                    objModuleToUserGroupSectionsInfoSource.STModuleToUserGroupSectionSortOrder = iOrderIndex;
                    objModuleToUserGroupSectionsInfoSource.STUserGroupSectionID = objUserGroupSectionsInfoTarget.ADUserGroupSectionID;
                    //Update
                    objSTModuleToUserGroupSectionController.UpdateObject(objModuleToUserGroupSectionsInfoSource);
                    //((UserManagementModule)Module).InitializeTreeList(fld_trlstUserGroup);
                    ((UserManagementModule)Module).RefreshTreeList(fld_trlstUserGroup, targetNode);
                }
                else
                    return;
            }
        }

        private void fld_trlstUserGroup_DragOver(object sender, DragEventArgs e)
        {
            TreeListHitInfo hi = fld_trlstUserGroup.CalcHitInfo(fld_trlstUserGroup.PointToClient(new Point(e.X, e.Y)));
            TreeListNode node = GetDragNode(e.Data);
            if (node == null)
            {
                if (hi.HitInfoType == HitInfoType.Empty || hi.Node != null)
                    e.Effect = DragDropEffects.Move;
                else
                    e.Effect = DragDropEffects.None;
            }
        }

        private void fld_trlstUserGroup_MouseDown(object sender, MouseEventArgs e)
        {
            downHitInfo = null;
            TreeListHitInfo hitInfo = fld_trlstUserGroup.CalcHitInfo(new Point(e.X,e.Y));
            if (Control.ModifierKeys != Keys.None) return;
            if (e.Button == MouseButtons.Left)
                downHitInfo = hitInfo;
        }



        private TreeListNode GetDragNode(IDataObject data)
        {
            return data.GetData(typeof(TreeListNode)) as TreeListNode;
        }

        private void fld_trlstUserGroup_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left && downHitInfo != null)
            {
                Size dragSize = SystemInformation.DragSize;
                Rectangle dragRect = new Rectangle(new Point(downHitInfo.MousePoint.X - dragSize.Width / 2,
                    downHitInfo.MousePoint.Y - dragSize.Height / 2), dragSize);

                if (!dragRect.Contains(new Point(e.X, e.Y)))
                {
                    fld_trlstUserGroup.DoDragDrop(downHitInfo, DragDropEffects.All);
                    downHitInfo = null;
                }
            }
        }
        #endregion

        private void fld_lstPermission_Click(object sender, EventArgs e)
        {
            ShowPrivileges();
        }

        private void fld_lstPermission_SelectedValueChanged(object sender, EventArgs e)
        {
            ShowPrivileges();
        }
    }
}